﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using giaoxuhaison.Models;
using System.Web.Security;
using System.IO;
using giaoxuhaison.Common;
using giaoxuhaison.MembershipServices;
using System.Data.Entity;
using System.Data;
using System.Configuration;

namespace giaoxuhaison.Controllers
{
    public class CategoriesController : Controller
    {
        //
        // GET: /Categories/
        private IBuildGridDataHelper<SpecialNewsModels> _gridhelper;
        private IBuildGridDataHelper<SpecialNewsModels> _gridhelperSpecNewsAll;
        private IBuildGridDataHelper<ImagesModels> _gridhelperImage;
        private IBuildGridDataHelper<ImagesModels> _gridhelperImageAll;
        private IBuildGridDataHelper<VideoModels> _gridhelperVideo;
        private IBuildGridDataHelper<VideoModels> _gridhelperVideoAll;  
        private bool Initialized = false;
        private gxhaisonEntities conn = new gxhaisonEntities();
        
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CategoryGroup(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstGroup"] = GetListGroup(GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }

        public ActionResult CategoryDetail(int CategoryID, int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstCategory"] = GetCategoryDetail(CategoryID);
            ViewData["lstOtherCategory"] = GetOtherCategory(CategoryID, GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }

        public ActionResult ImgVideoGroup(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstImg"] = GetImagesVideos(GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }
        public ActionResult ImgDetail(int ImgVideoID, int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstImg"] = GetDetailImages(ImgVideoID);
            ViewData["lstFiles"] = GetListFile(ImgVideoID);
            ViewData["lstOtherImg"] = GetOtherImg(ImgVideoID, GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }

        public ActionResult PanelImages()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            var ImgGrp = 40;
            ViewData["lstImg"] = GetImagesVideos(ImgGrp);
            return PartialView();
        }

        public ActionResult SadNewsGroup(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstNews"] = GetSpecialNews(GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }
        public ActionResult SadNewsDetail(int NewsID, int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstNews"] = GetSadNewsDetail(NewsID);
            ViewData["lstOtherNews"] = GetOtherSadNews(NewsID, GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }

        public ActionResult HappyNewsGroup(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstNews"] = GetSpecialNews(GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }
        public ActionResult HappyNewsDetail(int NewsID, int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstNews"] = GetSadNewsDetail(NewsID);
            ViewData["lstOtherNews"] = GetOtherSadNews(NewsID, GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }

        public ActionResult NewLeftHappy(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewData["lstNews"] = GetNewHappyNews(GroupID);
            return PartialView();
        }
        public ActionResult NewLeftSad(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewData["lstNews"] = GetNewSadNews(GroupID);
            return PartialView();
        }

        /*--Định nghĩa các hàm lấy dữ liệu*/
        private List<vw_CategoriesAll> GetListGroup(int GroupID)
        {
            var lstItem = conn.vw_CategoriesAll.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }

        private List<vw_CategoriesAll> GetCategoryDetail(int CategoryID)
        {
            var lstItem = conn.vw_CategoriesAll.Where(t => t.Locked == false && t.CategoryID == CategoryID).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }
        
        private List<vw_CategoriesAll> GetOtherCategory(int CategoryID, int GroupID)
        {
            var lstItem = conn.vw_CategoriesAll.Where(t => t.Locked == false && t.CategoryID != CategoryID && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(5).ToList();
            return lstItem;
        }

        private List<ImagesVideosAll> GetImagesVideos(int GroupID)
        {
            var lstItem = conn.ImagesVideosAlls.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).ToList(); ;
            return lstItem;
        }

        private List<vw_SpecialNewsAll> GetSpecialNews(int GroupID)
        {
            var lstItem = conn.vw_SpecialNewsAll.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).ToList(); ;
            return lstItem;
        }
        private List<vw_SpecialNewsAll> GetSadNewsDetail(int NewsID)
        {
            var lstItem = conn.vw_SpecialNewsAll.Where(t => t.Locked == false && t.NewsID == NewsID).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }
        private List<vw_SpecialNewsAll> GetOtherSadNews(int NewsID, int GroupID)
        {
            var lstItem = conn.vw_SpecialNewsAll.Where(t => t.Locked == false && t.NewsID != NewsID && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(5).ToList();
            return lstItem;
        }
        private List<vw_SpecialNewsAll> GetNewHappyNews(int GroupID)
        {
            var lstItem = conn.vw_SpecialNewsAll.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(2).ToList();
            return lstItem;
        }
        private List<vw_SpecialNewsAll> GetNewSadNews(int GroupID)
        {
            var lstItem = conn.vw_SpecialNewsAll.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(1).ToList();
            return lstItem;
        }

        private List<ImagesVideosAll> GetDetailImages(int ImgVideoID)
        {
            var lstItem = conn.ImagesVideosAlls.Where(t => t.Locked == false && t.ImgVideoID == ImgVideoID).OrderByDescending(t => t.CreationDate).ToList(); ;
            return lstItem;
        }

        private List<string> GetListFile(int ImgVideoID)
        {
            var lstItem = conn.ImagesVideosAlls.Where(t => t.Locked == false && t.ImgVideoID == ImgVideoID).OrderByDescending(t => t.CreationDate).ToList(); ;
            List<string> lstFiles;
            var strHost = Server.MapPath("~");
            lstFiles = null;
            if (lstItem != null && lstItem.Count > 0)
            {
                lstFiles = Directory.EnumerateFiles(Server.MapPath(lstItem[0].ImageContentPath)).ToList();
                if(lstFiles.Count > 0)
                {
                    for (int i = 0; i < lstFiles.Count; i++)
                    {
                        lstFiles[i] = lstFiles[i].ToString().Replace(strHost, "~\\");
                    }
                }
            }

            return lstFiles;            
        }
        /*end*/
        private List<ImagesVideosAll> GetOtherImg(int ImgVideoID, int GroupID)
        {
            var lstItem = conn.ImagesVideosAlls.Where(t => t.Locked == false && t.ImgVideoID != ImgVideoID && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(5).ToList();
            return lstItem;
        }

        private List<LinkPath> GetLinkPath(int GroupID)
        {
            var lstItem = conn.LinkPaths.Where(t => t.GroupID == GroupID).ToList();
            return lstItem;
        }

        /*phan quan tri*/
        /* quan tri tin vui/ tin buon */
        public ActionResult ManageSpecialNews()
        {
            if (Request.IsAuthenticated)
            {
                ViewData["lstSpecNews"] = GetListSpecial();
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }
        private List<ListGroupModels> GetListSpecial()
        {
            List<ListGroupModels> lst = new List<ListGroupModels>();
            ListGroupModels item = new ListGroupModels();
            ListGroupModels item1 = new ListGroupModels();
            item.GroupID = 38;
            item.GroupName = "Tin vui";
            lst.Add(item);

            item1.GroupID = 39;
            item1.GroupName = "Tin buồn";
            lst.Add(item1);

            return lst;
        }

        private string[] CreateRowsJSonSpecNewsAll(SpecialNewsModels model)
        {
            List<string> result = new List<string>();
            string format = "dd-mm-yyyy";
            result.Add(model.NewsID.ToString());
            result.Add(model.GroupID.ToString());
            result.Add(model.GroupName);
            result.Add(model.Subject);
            result.Add(model.ImageContentUrl);
            result.Add(model.ShortcutText);
            result.Add(model.Contents);
            result.Add(model.Locked.ToString());
            result.Add(model.CreationDate.ToShortDateString());
            return result.ToArray();

        }

        private void InitHelperLabelAll()
        {
            /*
             * Hungnvv : 03/04/2013
             */

            IEntityHelper entity = new EntityHelper();
            IPageCalculator pageCalc = new PageCalculator();
            ISortBuilder _sortBuilder = new SortBuilder(entity);
            IFilterBuilder _filterBuilder = new FilterBuilder(entity);

            //this._retrieveHandler = new RetrieveHandler(entity);
            this._gridhelperSpecNewsAll = new BuildGridDataHelper<SpecialNewsModels>(pageCalc, entity, _sortBuilder, _filterBuilder);

            Initialized = true;

            return;
        }
        public string GetAllSpecNews(string Condition_Find, string sortName, string sortOrder, int rowNumber, int rowId,
            int page, string searchField, string searchOper, string searchString)
        {
            if (!Initialized) InitHelperLabelAll();

            SpecialNewsModels model = new SpecialNewsModels();
            model.Condition_Find = Condition_Find;

            return _gridhelperSpecNewsAll.BuildDataForGrid(GetListSpecNews(model), CreateRowsJSonSpecNewsAll,
              sortName, "desc", rowNumber, rowId, page, searchField, searchOper, searchString);

        }

        private List<SpecialNewsModels> GetListSpecNews(SpecialNewsModels modelNewsAll)
        {

            var Item = conn.SpecialNewsAlls.Where(t => (t.Subject.Contains(modelNewsAll.Condition_Find) || t.ShortcutText.Contains(modelNewsAll.Condition_Find) || t.Contents.Contains(modelNewsAll.Condition_Find))).OrderByDescending(t => t.CreationDate).ToList();

            List<SpecialNewsModels> lst = new List<SpecialNewsModels>();

            foreach (var t in Item)
            {
                SpecialNewsModels model = new SpecialNewsModels();

                model.Condition_Find = t.Subject;
                model.NewsID = t.NewsID;
                model.GroupID = t.GroupID;
                if(t.GroupID == 38)
                {
                    model.GroupName = "Tin vui";
                }
                else
                {
                    model.GroupName = "Tin buồn";
                }
                model.Subject = t.Subject;
                model.ImageContentUrl = t.ImageContentUrl;
                model.ShortcutText = t.ShortcutText;
                model.Contents = t.Contents;
                model.Locked = t.Locked;
                model.CreationDate = t.CreationDate;
                lst.Add(model);
            }

            return lst;
        }

        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult ManageSpecialNews(SpecialNewsModels model)
        {
            //if (ModelState.IsValid)
            if (ValidateSpecNews(model))
            {
                SpecialNewsAll Item = new SpecialNewsAll();
                Item.NewsID = model.NewsID;
                Item.GroupID = model.GroupID;
                Item.Subject = model.Subject;
                if (model.GroupID == 38) //tin vui
                {
                    if (model.ImageContentUrl.ToString().IndexOf("/") > 0)
                    {
                        Item.ImageContentUrl = model.ImageContentUrl;
                    }
                    else
                    {
                        Item.ImageContentUrl = ConfigurationManager.AppSettings["SpecNewsPath"] + "/Happy/" + model.ImageContentUrl;// get default directory from web.config
                    }
                }
                else //tin buon
                {
                    if (model.ImageContentUrl.ToString().IndexOf("/") > 0)
                    {
                        Item.ImageContentUrl = model.ImageContentUrl;
                    }
                    else
                    {
                        Item.ImageContentUrl = ConfigurationManager.AppSettings["SpecNewsPath"] + "/Sad/" + model.ImageContentUrl;// get default directory from web.config
                    }
                }                
                Item.ShortcutText = model.ShortcutText;
                Item.Contents = model.Contents;
                Item.Locked = model.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = model.CreationDate;
                Item.LastUpdatedBy = AuthConfig.UserInfo.UserID;
                Item.LastUpdatedDate = DateTime.Now;

                try
                {
                    if (model.NewsID == null || model.NewsID.ToString() == "" || model.NewsID == 0)//insert
                    {
                        conn.SpecialNewsAlls.AddObject(Item);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Thêm mới thành công!");
                    }
                    else //update
                    {

                        conn.SpecialNewsAlls.Attach(Item);
                        conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Cập nhật thành công!");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            ViewData["lstSpecNews"] = GetListSpecial();
            return View(model);
        }

        private bool ValidateSpecNews(SpecialNewsModels model)
        {
            if (model.Subject == null || model.Subject.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tiêu đề!");
                return false;
            }
            if (model.ImageContentUrl == null || model.ImageContentUrl.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui chọn nhập hình đại diện!");
                return false;
            }
            if (model.ShortcutText == null || model.ShortcutText.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tóm tắt nội dung!");
                return false;
            }            
            if (model.Contents == null || model.Contents.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập nội dung tin!");
                return false;
            }
            if (model.CreationDate == null || model.CreationDate.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập ngày!");
                return false;
            }
            return true;
        }

        public ActionResult DeleteSpecNews(string NewsID)
        {
            if (NewsID.ToString() != "" && NewsID != "0")
            {
                SpecialNewsAll model = new SpecialNewsAll();
                int strLabelID = int.Parse(NewsID);

                model = (SpecialNewsAll)conn.SpecialNewsAlls.Where(t => t.NewsID == strLabelID).SingleOrDefault();

                try
                {
                    conn.SpecialNewsAlls.DeleteObject(model);
                    conn.SaveChanges();
                    ModelState.AddModelError("", "Xóa dữ liệu thành công!");
                    return Json("Xóa dữ liệu thành công", JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {

                    return Json("Xóa dữ liệu lỗi, vui lòng liên hệ quản trị hệ thống!", JsonRequestBehavior.AllowGet);
                }
            }
            //return RedirectToAction("DeleteNewsCatalogueSuccess");
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        /*xuly phan video*/
        public ActionResult NewVideo(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewData["lstNews"] = GetNewVideo(GroupID);
            return PartialView();
        }
        private List<vw_ImageVideoAll> GetNewVideo(int GroupID)
        {
            var lstItem = conn.vw_ImageVideoAll.Where(t => t.Locked == false && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(2).ToList();
            return lstItem;
        }
        public ActionResult VideoDetail(int VideoID, int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstVideos"] = GetVideoDetail(VideoID);
            ViewData["lstOtherVideos"] = GetOtherVideos(VideoID, GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }
        private List<vw_ImageVideoAll> GetVideoDetail(int VideoID)
        {
            var lstItem = conn.vw_ImageVideoAll.Where(t => t.Locked == false && t.ImgVideoID == VideoID).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }
        private List<vw_ImageVideoAll> GetOtherVideos(int VideoID, int GroupID)
        {
            var lstItem = conn.vw_ImageVideoAll.Where(t => t.Locked == false && t.ImgVideoID != VideoID && t.GroupID == GroupID).OrderByDescending(t => t.CreationDate).Take(10).ToList();
            return lstItem;
        }
        /*end video*/
        /*phan download tai lieu*/
        public ActionResult DownloadDocument(int GroupID)
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            ViewData["lstDocument"] = GetDocument(GroupID);
            ViewData["lstLinkPath"] = GetLinkPath(GroupID);
            return PartialView();
        }

        private List<vw_DocumentsAll> GetDocument(int GroupID)
        {
            var lstItem = conn.vw_DocumentsAll.Where(t => t.Locked == false).OrderByDescending(t => t.CreationDate).ToList();
            return lstItem;
        }

        /*Phan quan ly video & image*/

        public ActionResult ManageImages()
        {
            if (Request.IsAuthenticated)
            {
                //ViewData["lstSpecNews"] = GetListSpecial();
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }

        private string[] CreateRowsJSonImagesAll(ImagesModels model)
        {
            List<string> result = new List<string>();
            string format = "dd-mm-yyyy";
            result.Add(model.ImgVideoID.ToString());
            result.Add(model.Subject.ToString());
            result.Add(model.IntroImageUrl);
            result.Add(model.ImageContentPath);
            result.Add(model.Locked.ToString());
            result.Add(model.CreationDate.ToShortDateString());
            return result.ToArray();

        }

        private void InitHelperImagesAll()
        {
            /*
             * Hungnvv : 03/04/2013
             */

            IEntityHelper entity = new EntityHelper();
            IPageCalculator pageCalc = new PageCalculator();
            ISortBuilder _sortBuilder = new SortBuilder(entity);
            IFilterBuilder _filterBuilder = new FilterBuilder(entity);

            //this._retrieveHandler = new RetrieveHandler(entity);
            this._gridhelperImageAll = new BuildGridDataHelper<ImagesModels>(pageCalc, entity, _sortBuilder, _filterBuilder);

            Initialized = true;

            return;
        }
        public string GetAllImages(string Condition_Find, string sortName, string sortOrder, int rowNumber, int rowId,
            int page, string searchField, string searchOper, string searchString)
        {
            if (!Initialized) InitHelperImagesAll();

            ImagesModels model = new ImagesModels();
            model.Condition_Find = Condition_Find;

            return _gridhelperImageAll.BuildDataForGrid(GetListImages(model), CreateRowsJSonImagesAll,
              sortName, "desc", rowNumber, rowId, page, searchField, searchOper, searchString);

        }

        private List<ImagesModels> GetListImages(ImagesModels modelNewsAll)
        {

            var Item = conn.ImagesVideosAlls.Where(t => t.Subject.Contains(modelNewsAll.Condition_Find) && t.GroupID == 40).OrderByDescending(t => t.CreationDate).ToList();

            List<ImagesModels> lst = new List<ImagesModels>();

            foreach (var t in Item)
            {
                ImagesModels model = new ImagesModels();

                model.Condition_Find = t.Subject;
                model.ImgVideoID = t.ImgVideoID;
                model.Subject = t.Subject;
                model.IntroImageUrl = t.IntroImageUrl;
                model.ImageContentPath = t.ImageContentPath;
                model.Locked = t.Locked;
                model.CreationDate = t.CreationDate;
                lst.Add(model);
            }

            return lst;
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ManageImages(ImagesModels model)
        {
            //if (ModelState.IsValid)
            if (ValidateImages(model))
            {
                ImagesVideosAll Item = new ImagesVideosAll();
                Item.ImgVideoID = model.ImgVideoID;
                Item.GroupID = 40;
                Item.GroupType = 1;
                Item.Subject = model.Subject;
                Item.IntroImageUrl = model.IntroImageUrl;
                if (model.IntroImageUrl.ToString().IndexOf("/") > 0)
                {
                    Item.IntroImageUrl = model.IntroImageUrl;
                }
                else
                {
                    Item.IntroImageUrl = ConfigurationManager.AppSettings["ImagesPath"] + model.ImageContentPath + '/' + model.IntroImageUrl;// get default directory from web.config
                }

                if (model.ImageContentPath.ToString().IndexOf("/") > 0)
                {
                    Item.ImageContentPath = model.ImageContentPath;
                }
                else
                {
                    Item.ImageContentPath = ConfigurationManager.AppSettings["ImagesPath"] + model.ImageContentPath;
                }
                //Item.ImageContentPath = model.ImageContentPath;
                Item.Locked = model.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = model.CreationDate;
                Item.LastUpdatedBy = AuthConfig.UserInfo.UserID;
                Item.LastUpdatedDate = DateTime.Now;

                try
                {
                    if (model.ImgVideoID == null || model.ImgVideoID.ToString() == "" || model.ImgVideoID == 0)//insert
                    {
                        conn.ImagesVideosAlls.AddObject(Item);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Thêm mới thành công!");
                    }
                    else //update
                    {

                        conn.ImagesVideosAlls.Attach(Item);
                        conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Cập nhật thành công!");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            ViewData["lstSpecNews"] = GetListSpecial();
            return View(model);
        }

        private bool ValidateImages(ImagesModels model)
        {
            if (model.Subject == null || model.Subject.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tiêu đề!");
                return false;
            }
            if (model.IntroImageUrl == null || model.IntroImageUrl.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui chọn nhập hình đại diện!");
                return false;
            }
            if (model.ImageContentPath == null || model.ImageContentPath.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập đường dẫn chứa hình ảnh!");
                return false;
            }            
            if (model.CreationDate == null || model.CreationDate.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập ngày!");
                return false;
            }
            return true;
        }
        public ActionResult DeleteImages(string ImgVideoID)
        {
            if (ImgVideoID.ToString() != "" && ImgVideoID != "0")
            {
                ImagesVideosAll model = new ImagesVideosAll();
                int strLabelID = int.Parse(ImgVideoID);

                model = (ImagesVideosAll)conn.ImagesVideosAlls.Where(t => t.ImgVideoID == strLabelID).SingleOrDefault();

                try
                {
                    conn.ImagesVideosAlls.DeleteObject(model);
                    conn.SaveChanges();
                    ModelState.AddModelError("", "Xóa dữ liệu thành công!");
                    return Json("Xóa dữ liệu thành công", JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {

                    return Json("Xóa dữ liệu lỗi, vui lòng liên hệ quản trị hệ thống!", JsonRequestBehavior.AllowGet);
                }
            }
            //return RedirectToAction("DeleteNewsCatalogueSuccess");
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }

        /*video*/
        public ActionResult ManageVideos()
        {
            if (Request.IsAuthenticated)
            {
                //ViewData["lstSpecNews"] = GetListSpecial();
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Admin"); ;
            }
        }
        private string[] CreateRowsJSonVideosAll(VideoModels model)
        {
            List<string> result = new List<string>();
            string format = "dd-mm-yyyy";
            result.Add(model.ImgVideoID.ToString());
            result.Add(model.Subject.ToString());
            result.Add(model.ImageContentPath);
            result.Add(model.Locked.ToString());
            result.Add(model.CreationDate.ToShortDateString());
            return result.ToArray();

        }

        private void InitHelperVideosAll()
        {
            /*
             * Hungnvv : 03/04/2013
             */

            IEntityHelper entity = new EntityHelper();
            IPageCalculator pageCalc = new PageCalculator();
            ISortBuilder _sortBuilder = new SortBuilder(entity);
            IFilterBuilder _filterBuilder = new FilterBuilder(entity);

            //this._retrieveHandler = new RetrieveHandler(entity);
            this._gridhelperVideoAll = new BuildGridDataHelper<VideoModels>(pageCalc, entity, _sortBuilder, _filterBuilder);

            Initialized = true;

            return;
        }
        public string GetAllVideos(string Condition_Find, string sortName, string sortOrder, int rowNumber, int rowId,
            int page, string searchField, string searchOper, string searchString)
        {
            if (!Initialized) InitHelperVideosAll();

            VideoModels model = new VideoModels();
            model.Condition_Find = Condition_Find;

            return _gridhelperVideoAll.BuildDataForGrid(GetListVideos(model), CreateRowsJSonVideosAll,
              sortName, "desc", rowNumber, rowId, page, searchField, searchOper, searchString);

        }

        private List<VideoModels> GetListVideos(VideoModels modelNewsAll)
        {

            var Item = conn.ImagesVideosAlls.Where(t => t.Subject.Contains(modelNewsAll.Condition_Find) && t.GroupID == 41).OrderByDescending(t => t.CreationDate).ToList();

            List<VideoModels> lst = new List<VideoModels>();

            foreach (var t in Item)
            {
                VideoModels model = new VideoModels();

                model.Condition_Find = t.Subject;
                model.ImgVideoID = t.ImgVideoID;
                model.Subject = t.Subject;
                model.ImageContentPath = t.ImageContentPath;
                model.Locked = t.Locked;
                model.CreationDate = t.CreationDate;
                lst.Add(model);
            }

            return lst;
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ManageVideos(VideoModels model)
        {
            //if (ModelState.IsValid)
            if (ValidateVideos(model))
            {
                ImagesVideosAll Item = new ImagesVideosAll();
                Item.ImgVideoID = model.ImgVideoID;
                Item.GroupID = 41;
                Item.GroupType = 2;
                Item.Subject = model.Subject;
                Item.IntroImageUrl = "video";
                Item.ImageContentPath = model.ImageContentPath;
                Item.Locked = model.Locked;
                Item.CreationBy = AuthConfig.UserInfo.UserID;
                Item.CreationDate = model.CreationDate;
                Item.LastUpdatedBy = AuthConfig.UserInfo.UserID;
                Item.LastUpdatedDate = DateTime.Now;

                try
                {
                    if (model.ImgVideoID == null || model.ImgVideoID.ToString() == "" || model.ImgVideoID == 0)//insert
                    {
                        conn.ImagesVideosAlls.AddObject(Item);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Thêm mới thành công!");
                    }
                    else //update
                    {

                        conn.ImagesVideosAlls.Attach(Item);
                        conn.ObjectStateManager.ChangeObjectState(Item, EntityState.Modified);
                        conn.SaveChanges();
                        ModelState.AddModelError("", "Cập nhật thành công!");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", ValidateMessages.ErrorDescription(MembershipStatus.Error));
                }
            }

            ViewData["lstSpecNews"] = GetListSpecial();
            return View(model);
        }

        private bool ValidateVideos(VideoModels model)
        {
            if (model.Subject == null || model.Subject.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập tiêu đề!");
                return false;
            }
            if (model.ImageContentPath == null || model.ImageContentPath.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập đường dẫn chứa video!");
                return false;
            }
            if (model.CreationDate == null || model.CreationDate.ToString() == "")
            {
                ModelState.AddModelError("", "Xin vui lòng nhập ngày!");
                return false;
            }
            return true;
        }
        public ActionResult DeleteVideos(string ImgVideoID)
        {
            if (ImgVideoID.ToString() != "" && ImgVideoID != "0")
            {
                ImagesVideosAll model = new ImagesVideosAll();
                int strLabelID = int.Parse(ImgVideoID);

                model = (ImagesVideosAll)conn.ImagesVideosAlls.Where(t => t.ImgVideoID == strLabelID).SingleOrDefault();

                try
                {
                    conn.ImagesVideosAlls.DeleteObject(model);
                    conn.SaveChanges();
                    ModelState.AddModelError("", "Xóa dữ liệu thành công!");
                    return Json("Xóa dữ liệu thành công", JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {

                    return Json("Xóa dữ liệu lỗi, vui lòng liên hệ quản trị hệ thống!", JsonRequestBehavior.AllowGet);
                }
            }
            //return RedirectToAction("DeleteNewsCatalogueSuccess");
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
    }
}
